package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Article;
import com.example.demo.entity.Category;
import com.example.demo.entity.Tag;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoryService;
import com.example.demo.service.TagService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户文章管理控制器
 * 处理用户的文章发布、编辑等操作
 */
@RestController
@RequestMapping("/api/user/articles")
@com.example.demo.annotation.RequiresRole(value = {"USER", "ADMIN"}, logical = com.example.demo.annotation.RequiresRole.Logical.OR)
public class UserArticleController {
    
    private static final Logger log = LoggerFactory.getLogger(UserArticleController.class);
    
    private final ArticleService articleService;
    private final CategoryService categoryService;
    private final TagService tagService;
    
    public UserArticleController(ArticleService articleService, 
                               CategoryService categoryService,
                               TagService tagService) {
        this.articleService = articleService;
        this.categoryService = categoryService;
        this.tagService = tagService;
    }
    
    /**
     * 获取当前用户的文章列表
     */
    @GetMapping
    public Result<Map<String, Object>> getUserArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            HttpServletRequest request) {
        
        Long userId = getCurrentUserId(request);
        log.info("获取用户{}的文章列表，页码：{}，大小：{}", userId, page, size);
        
        try {
            // 使用现有的按作者查询文章的方法
            ArticleService.PageResult<Article> result = articleService.getArticlesByAuthor(userId, page, size);
            
            Map<String, Object> data = new HashMap<>();
            data.put("articles", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", result.getPage());
            data.put("size", result.getSize());
            data.put("totalPages", result.getPages());
            
            return Result.success("获取文章列表成功", data);
            
        } catch (Exception e) {
            log.error("获取用户文章列表失败", e);
            return Result.error("获取文章列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取文章详情（只能获取自己的文章）
     */
    @GetMapping("/{id}")
    public Result<Article> getArticleById(@PathVariable Long id, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        log.info("用户{}获取文章{}详情", userId, id);
        
        try {
            Article article = articleService.getArticleById(id, false);
            
            if (article == null) {
                return Result.error("文章不存在");
            }
            
            // 检查文章是否属于当前用户
            if (!article.getAuthorId().equals(userId)) {
                return Result.error("无权访问此文章");
            }
            
            return Result.success("获取文章详情成功", article);
            
        } catch (Exception e) {
            log.error("获取文章详情失败", e);
            return Result.error("获取文章详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建新文章
     */
    @PostMapping
    public Result<Article> createArticle(@Valid @RequestBody Article article, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        log.info("用户{}创建新文章：{}", userId, article.getTitle());
        
        try {
            // 设置作者信息
            article.setAuthorId(userId);
            article.setCreateTime(LocalDateTime.now());
            article.setUpdateTime(LocalDateTime.now());
            
            // 如果没有设置状态，默认为草稿
            if (article.getStatus() == null) {
                article.setStatus(0); // 草稿
            }
            
            // 从请求中获取标签（简化处理）
            List<String> tagNames = java.util.Arrays.asList(); // 暂时为空，后续改进
            
            Article savedArticle = articleService.createArticle(article, tagNames);
            return Result.success("文章创建成功", savedArticle);
            
        } catch (Exception e) {
            log.error("创建文章失败", e);
            return Result.error("创建文章失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新文章
     */
    @PutMapping("/{id}")
    public Result<String> updateArticle(@PathVariable Long id, 
                                      @Valid @RequestBody Article article, 
                                      HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        log.info("用户{}更新文章{}：{}", userId, id, article.getTitle());
        
        try {
            // 检查文章是否存在且属于当前用户
            Article existingArticle = articleService.getArticleById(id, false);
            if (existingArticle == null) {
                return Result.error("文章不存在");
            }
            
            if (!existingArticle.getAuthorId().equals(userId)) {
                return Result.error("无权修改此文章");
            }
            
            // 设置更新信息
            article.setId(id);
            article.setAuthorId(userId);
            article.setUpdateTime(LocalDateTime.now());
            
            // 从请求中获取标签（简化处理）
            List<String> tagNames = java.util.Arrays.asList(); // 暂时为空，后续改进
            
            articleService.updateArticle(article, tagNames);
            return Result.success("文章更新成功");
            
        } catch (Exception e) {
            log.error("更新文章失败", e);
            return Result.error("更新文章失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除文章
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteArticle(@PathVariable Long id, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        log.info("用户{}删除文章{}", userId, id);
        
        try {
            // 检查文章是否存在且属于当前用户
            Article existingArticle = articleService.getArticleById(id, false);
            if (existingArticle == null) {
                return Result.error("文章不存在");
            }
            
            if (!existingArticle.getAuthorId().equals(userId)) {
                return Result.error("无权删除此文章");
            }
            
            boolean success = articleService.deleteArticle(id);
            if (success) {
                return Result.success("文章删除成功");
            } else {
                return Result.error("文章删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return Result.error("删除文章失败：" + e.getMessage());
        }
    }
    
    /**
     * 发布/取消发布文章
     */
    @PostMapping("/{id}/publish")
    public Result<String> togglePublish(@PathVariable Long id, 
                                      @RequestParam Integer status, 
                                      HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        log.info("用户{}变更文章{}发布状态为：{}", userId, id, status);
        
        try {
            // 检查文章是否存在且属于当前用户
            Article existingArticle = articleService.getArticleById(id, false);
            if (existingArticle == null) {
                return Result.error("文章不存在");
            }
            
            if (!existingArticle.getAuthorId().equals(userId)) {
                return Result.error("无权修改此文章");
            }
            
            boolean success;
            String statusText;
            if (status == 1) {
                success = articleService.publishArticle(id);
                statusText = "已发布";
            } else {
                success = articleService.hideArticle(id);
                statusText = "草稿";
            }
            
            if (success) {
                return Result.success("文章状态更新为：" + statusText);
            } else {
                return Result.error("更新文章状态失败");
            }
            
        } catch (Exception e) {
            log.error("更新文章发布状态失败", e);
            return Result.error("更新文章状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有分类（用于文章编辑）
     */
    @GetMapping("/categories")
    public Result<List<Category>> getCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return Result.success("获取分类列表成功", categories);
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            return Result.error("获取分类列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有标签（用于文章编辑）
     */
    @GetMapping("/tags")
    public Result<List<Tag>> getTags() {
        try {
            List<Tag> tags = tagService.getAllTags();
            return Result.success("获取标签列表成功", tags);
        } catch (Exception e) {
            log.error("获取标签列表失败", e);
            return Result.error("获取标签列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 文章统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getArticleStats(HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        
        try {
            // 获取用户的文章统计（使用现有方法）
            ArticleService.PageResult<Article> allArticles = articleService.getArticlesByAuthor(userId, 1, 1000);
            
            long totalArticles = allArticles.getTotal();
            long publishedArticles = allArticles.getRecords().stream().mapToLong(a -> a.getStatus() == 1 ? 1 : 0).sum();
            long draftArticles = allArticles.getRecords().stream().mapToLong(a -> a.getStatus() == 0 ? 1 : 0).sum();
            long totalViews = allArticles.getRecords().stream().mapToLong(a -> a.getViewCount() != null ? a.getViewCount() : 0).sum();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalArticles", totalArticles);
            stats.put("publishedArticles", publishedArticles);
            stats.put("draftArticles", draftArticles);
            stats.put("totalViews", totalViews);
            
            return Result.success("获取文章统计成功", stats);
            
        } catch (Exception e) {
            log.error("获取文章统计失败", e);
            return Result.error("获取文章统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userId = request.getAttribute("currentUserId");
        if (userId instanceof Long) {
            return (Long) userId;
        }
        throw new RuntimeException("未获取到用户身份信息，请重新登录");
    }
}
